<?php


namespace app\api\controller;

use app\api\controller\ApiBase;
use app\api\model\AdminUser;
use app\api\model\Role as RoleModel;
use think\facade\Db;
use think\facade\Request;

//use app\api\model\Role as RoleModel;

class User extends ApiBase
{
    public function getUserList(\think\Request $request){
        $username=$request->token_user_name;

        $adminUser = AdminUser::select()->toArray();

        return renderSuccess('',$adminUser);

    }

    public function add(){
        $data = Request::post();
        $time = strtotime('now');
        $has_user = AdminUser::where('username',$data['username'])->find();
//        dump($has_user);exit;
        if(!empty($has_user)){
            return renderError('已存在此用户');
        }

        $user_data = [
          'name'=>$data['name'],
          'username'=>$data['username'],
          'password'=>MD5(MD5($data['password'])),
          'sort'=>$data['sort'],
          'create_time'=>$time
        ];

        Db::startTrans();
        try {
            $AdminUser =  AdminUser::create($user_data);
            $AdminUser->role()->save($data['roleIds']);
            // 提交事务
            Db::commit();
            return renderSuccess('添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return renderError($e->getMessage());
        }


    }

}